import { defineStore } from "pinia";
import { cartPost, cartPut } from "../api/user";
import { CartProductType, ProductType } from "../types/prod";
// import { cartGet } from "./../../../../../2205H5/Vue（C端）/vue-ts-2205/src/api/user";
import { cartGet } from "../api/user";
interface CartStateType {
  cartList: Array<CartProductType>;
}
export const useCart = defineStore("cart", {
  state: (): CartStateType => ({
    cartList: [],
  }),
  getters: {
    allInfo(state) {
      let allPrice = 0;
      let allCheck = true; //全选状态
      let allNum = 0;
      state.cartList.forEach((item) => {
        if (item.ischeck) {
          allPrice += item.num * item.originprice * 100;
        }
        if (!item.ischeck) {
          allCheck = false;
        }
        allNum += item.num;
      });
      return {
        allPrice,
        allCheck,
        allNum,
      };
    },
  },
  actions: {
    //新增
    async cartAddAction(prod: ProductType, userid: string) {
      for (let i = 0; i < this.cartList.length; i++) {
        if (prod.objectId == this.cartList[i].productid) {
          let { num, objectId } = this.cartList[i];
          await cartPut(objectId as string, { num: ++num }); //更新线上数据
          this.cartList[i].num++; //已有商品
          return;
        }
      }
      let cartObj = {
        ...prod,
        ischeck: true,
        num: 1,
        userid,
        productid: prod.objectId as string,
      };
      delete cartObj.objectId; //删除商品objectId
      let res = await cartPost(cartObj);
      console.log("新增成功", res);
      this.cartList.push({ ...cartObj, objectId: res.data.objectId }); //新商品
    },
    //全选
    cartAllCheckAction(allCheck: boolean) {
      this.cartList.forEach((item) => {
        item.ischeck = allCheck;
      });
    },
    // 根据用户id，初始化购物车数据
    async initCartAction(userid: string) {
      let res = await cartGet(userid);
      this.cartList = res.data.results;
    },
  },
  persist: {
    key: "pinia-cart-2206",
  },
});
